<template>
	<uni-file-picker
		v-model="value"
		:auto-upload="false"
		:limit="limit"
		:imageStyles="imageStyles"
        :del-icon="closeable"
		:file-mediatype="mediatype"
		@select="handleSelect"
		@progress="handleProgress"
		@success="handleSuccess"
		@delete="handleDelete"
		@fail="handleFail"
		ref="unifilepicker"
	>
		<slot></slot>
	</uni-file-picker>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
	modelValue: {
		type: Array,
		default: () => []
	},
	disabled: {
		type: Boolean,
		default: false
	},
	readonly:{
	   type:Boolean,
	   default:false
	},
	maxSize: {
		type: Number,
		default: -1
	},
	limit: {
		type: Number,
		default: 9
	},
	beforeRead: {
		type: Function,
		default: () => {}
	},
	afterRead: {
		type: Function,
		default: () => {}
	},
	imageStyles: {
		type: Object,
		default: () => {}
	},
	isDisu: {
		type: Boolean,
		default: false
	},
  closeable: {
		type: Boolean,
		default: true
	},
	clearFile:{
		type:Boolean,
		default:false
	},
	mediatype:{
		type:String,
		default:"image"
	}
})

const emit = defineEmits(['update:modelValue', 'onOversize','beforeDelete'])

const value = ref([...props.modelValue])
const unifilepicker=ref(null)
watch(
	() => props.modelValue,
	(newVal) => {
		value.value = [...newVal]
	},
	{ deep: true }
)

watch(value, (newVal) => {
	!props.isDisu&&emit('update:modelValue', newVal)
})

const handleSelect = (e) => {
	 try{
		 let file = e.tempFiles[0]
		 if (props.maxSize > 0 && file.size > props.maxSize) {
		 	emit('onOversize', file)
		 	return
		 }
		 if (props.beforeRead(file)) {
		 	!props.isDisu?props.afterRead(file):props.afterRead( e.tempFiles)
		 }
	 }catch(err){
		 console.log("选择错误的数据",err)
	 }
	
}

const handleProgress = (e) => {
	console.log(e)
}
const handleSuccess = (e) => {
	console.log(e)
}
const handleDelete = (e) => {
	props.clearFile&&emit('beforeDelete')
	
}
const handleFail = (e) => {
	console.log("上传失败了",e)
}
const clearFile=()=>{
	console.log("清除file");
	unifilepicker.value.clearFiles()
}
defineExpose({
	clearFile
})
</script>

<style lang="scss" scoped></style>
